package cn.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.demo.service.AccountService;

import java.io.IOException;

@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService retryService;

    @GetMapping("transfer1")
    public String transfer1() {
        try {
            retryService.transferAccounts1(1,2,10);
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            return "no";
        }
    }

    /**
     * 本类方法直接调用，事务失效，不回滚
     * @return
     */
    @GetMapping("transfer2")
    public String transfer2() {
        try {
            retryService.transferAccounts2(1,2,10);
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            return "no";
        }
    }

    /**
     * rollbackFor设置错误，事务失效，不回滚
     * @return
     */
    @GetMapping("transfer3")
    public String transfer3() {
        try {
            retryService.transferAccounts3(1,2,10);
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            return "no";
        }
    }

    /**
     * 非public方法开启事务，事务失效，不回滚
     * @return
     */
    @GetMapping("transfer4")
    public String transfer4() {
        try {
            retryService.transferAccounts4(1,2,10);
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            return "no";
        }
    }

    /**
     * 异常被catch掉，事务失效，不回滚
     * @return
     */
    @GetMapping("transfer5")
    public String transfer5() {
        try {
            retryService.transferAccounts5(1,2,10);
            return "yes";
        } catch (Exception e) {
            e.printStackTrace();
            return "no";
        }
    }

    /**
     * 编程式事务：循环体中只回滚发生异常的
     * @return
     */
    @GetMapping("transfer6")
    public String transfer6() {
        retryService.transferAccounts6();
        return "yes";
    }

    /**
     * spring事务和业务逻辑代码不在一个线程中
     * @return
     */
    @GetMapping("transfer7")
    public String transfer7() {
        retryService.transferAccounts7(1,2,10);
        return "yes";
    }

    /**
     * 抛出检查异常：事务不回滚
     * @return
     */
    @GetMapping("transfer8")
    public String transfer8() {
        try {
            retryService.transferAccounts8(1,2,10);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "yes";
    }
}
